<template>
  <div class="archived-view-content">
    <div class="archived-list-container">
      <!-- Search bar on its own line -->
      <div class="search-bar-archive-solo">
        <input type="text" v-model="searchQuery" placeholder="搜索历史库..." class="search-input" :disabled="isLoadingArchived">
      </div>

      <div class="select-all-bar">
        <div class="select-actions-group">
          <input type="checkbox" :checked="isAllSelected" @change="toggleSelectAll" id="select-all-archived" class="checkbox-style" :disabled="searchedFilteredAndSortedArchivedTodos.length === 0 || isLoadingArchived">
          <label for="select-all-archived" :class="{ 'disabled-label': searchedFilteredAndSortedArchivedTodos.length === 0 || isLoadingArchived }">全选</label>
          <button @click="deleteSelectedItems" :disabled="selectedCount === 0 || isLoadingArchived" class="delete-selected-button">
            <span class="button-icon">&#xE74D;</span> 删除选中
          </button>
        </div>
        
        <!-- Container for filters on the right -->
        <div class="filters-archive-right-group">
          <!-- Status Filter Controls -->
          <div class="filter-status-bar-archive">
            <span class="filter-label">状态:</span>
            <button @click="setFilterStatusArchive('all')" :class="{ 'active': filterStatusArchive === 'all' }">全部</button>
            <button @click="setFilterStatusArchive('active')" :class="{ 'active': filterStatusArchive === 'active' }">未完成</button>
            <button @click="setFilterStatusArchive('completed')" :class="{ 'active': filterStatusArchive === 'completed' }">已完成</button>
          </div>

          <!-- Priority Filter Controls -->
          <div class="filter-priority-bar-archive">
            <span class="filter-label">优先级:</span>
            <button @click="setFilterPriorityArchive('all')" :class="{ 'active': filterPriorityArchive === 'all' }">全部</button>
            <button @click="setFilterPriorityArchive(PRIORITIES.HIGH)" :class="{ 'active': filterPriorityArchive === PRIORITIES.HIGH }">
              <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span>{{ getPriorityText(PRIORITIES.HIGH) }}
            </button>
            <button @click="setFilterPriorityArchive(PRIORITIES.MEDIUM)" :class="{ 'active': filterPriorityArchive === PRIORITIES.MEDIUM }">
              <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span>{{ getPriorityText(PRIORITIES.MEDIUM) }}
            </button>
            <button @click="setFilterPriorityArchive(PRIORITIES.LOW)" :class="{ 'active': filterPriorityArchive === PRIORITIES.LOW }">
              <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span>{{ getPriorityText(PRIORITIES.LOW) }}
            </button>
            <button @click="setFilterPriorityArchive(PRIORITIES.NONE)" :class="{ 'active': filterPriorityArchive === PRIORITIES.NONE }">
              <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span>{{ getPriorityText(PRIORITIES.NONE) }}
            </button>
          </div>
        </div>
      </div>

      <div class="archived-list-section">
        <p v-if="isLoadingArchived" class="loading-message">正在加载历史记录...</p>
        <ul class="archived-list" v-else-if="paginatedArchivedTodos.length > 0">
          <li v-for="item in paginatedArchivedTodos" :key="item.id" :class="['archived-item', { 'completed': item.completed, 'selected': isItemSelected(item.id) }]">
            <input type="checkbox" :checked="isItemSelected(item.id)" @change.stop="toggleItemSelected(item.id)" class="item-checkbox checkbox-style">
            <div class="item-content-wrapper">
              <div class="item-main-info">
                <span
                  v-if="item.priority !== undefined && item.priority !== PRIORITIES.NONE"
                  class="priority-indicator-archived"
                  :style="{ backgroundColor: getPriorityColor(item.priority) }"
                  :title="getPriorityText(item.priority) + '优先级'"
                ></span>
                <span class="item-text" :title="item.text">{{ item.text }}</span>
              </div>
              <div class="item-meta-line">
                <span class="item-status">
                  ({{ item.completed ? '已完成' : '未完成' }}
                  <template v-if="item.completed && item.completedDate">
                    - 完成于: {{ new Date(item.completedDate).toLocaleString('zh-CN') }}
                  </template>
                  )
                </span>
                <span class="item-archived-date">
                  归档于: {{ item.archivedDate ? new Date(item.archivedDate).toLocaleString('zh-CN') : '未知日期' }}
                </span>
              </div>
            </div>
          </li>
        </ul>
        <p v-else-if="searchedFilteredAndSortedArchivedTodos.length === 0 && (searchQuery || filterPriorityArchive !== 'all')" class="empty-list-message">
          当前筛选条件下没有匹配的归档项。
        </p>
        <p v-else-if="!isLoadingArchived && getArchivedTodos.length === 0" class="empty-list-message">历史库是空的。</p>
      </div>
    </div>

    <!-- Pagination Controls -->
    <div class="pagination-controls-archive" v-if="totalPagesArchive > 1">
      <button @click="prevArchivePage" :disabled="currentPageArchive === 1" class="pagination-button">上一页</button>
      <span class="pagination-info">第 {{ currentPageArchive }} / {{ totalPagesArchive }} 页</span>
      <button @click="nextArchivePage" :disabled="currentPageArchive === totalPagesArchive" class="pagination-button">下一页</button>
    </div>

    <div class="archived-footer">
      <div class="priority-legend-container-archived">
        <div
          v-for="priorityKey in Object.keys(PRIORITY_CONFIG).filter(key => key !== 'NONE')"
          :key="priorityKey"
          class="legend-item"
        >
          <span
            class="legend-dot"
            :style="{ backgroundColor: PRIORITY_CONFIG[priorityKey].color }"
          ></span>
          <span class="legend-text">{{ PRIORITY_CONFIG[priorityKey].text }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import { PRIORITIES, PRIORITY_CONFIG, getPriorityText, getPriorityColor, getPriorityIcon } from '@/utils/priorityUtils';

export default {
  name: 'ArchivedView',
  data() {
    return {
      PRIORITIES,
      PRIORITY_CONFIG,
      searchQuery: '',
      selectedArchivedIds: [],
      isLoadingArchived: false,
      currentPageArchive: 1,
      itemsPerPageArchive: 15,
      filterPriorityArchive: 'all',
      filterStatusArchive: 'all',
    };
  },
  computed: {
    ...mapGetters([
      'getArchivedTodos',
      'archivedTodosLoadStatus'
    ]),
    sortedArchivedTodos() {
      return [...this.getArchivedTodos].sort((a, b) => {
        const dateA = a.archivedDate ? new Date(a.archivedDate).getTime() : 0;
        const dateB = b.archivedDate ? new Date(b.archivedDate).getTime() : 0;
        return dateB - dateA; // 最新归档的在前
      });
    },
    searchedFilteredAndSortedArchivedTodos() {
      let items = [...this.getArchivedTodos];

      if (this.searchQuery) {
        const lowerSearchQuery = this.searchQuery.toLowerCase();
        items = items.filter(item =>
          item.text.toLowerCase().includes(lowerSearchQuery)
        );
      }

      if (this.filterPriorityArchive !== 'all') {
        items = items.filter(item => item.priority === this.filterPriorityArchive);
      }

      if (this.filterStatusArchive === 'completed') {
        items = items.filter(item => item.completed);
      } else if (this.filterStatusArchive === 'active') {
        items = items.filter(item => !item.completed);
      }

      items.sort((a, b) => {
        const dateA = a.archivedDate ? new Date(a.archivedDate).getTime() : 0;
        const dateB = b.archivedDate ? new Date(b.archivedDate).getTime() : 0;
        return dateB - dateA;
      });

      return items;
    },
    totalPagesArchive() {
      if (!this.searchedFilteredAndSortedArchivedTodos || this.searchedFilteredAndSortedArchivedTodos.length === 0) {
        return 1;
      }
      return Math.ceil(this.searchedFilteredAndSortedArchivedTodos.length / this.itemsPerPageArchive);
    },
    paginatedArchivedTodos() {
      const startIndex = (this.currentPageArchive - 1) * this.itemsPerPageArchive;
      const endIndex = startIndex + this.itemsPerPageArchive;
      return this.searchedFilteredAndSortedArchivedTodos.slice(startIndex, endIndex);
    },
    selectedCount() {
      return this.selectedArchivedIds.length;
    },
    isAllSelected() {
      if (this.paginatedArchivedTodos.length === 0) {
        return false;
      }
      const currentPageItemIds = this.paginatedArchivedTodos.map(item => item.id);
      return currentPageItemIds.every(id => this.selectedArchivedIds.includes(id));
    }
  },
  methods: {
    ...mapActions([
      'deleteArchivedTodosBatch',
      'fetchArchivedTodosFromDisk'
    ]),
    getPriorityText,
    getPriorityColor,
    getPriorityIcon,
    isItemSelected(itemId) {
      return this.selectedArchivedIds.includes(itemId);
    },
    toggleItemSelected(itemId) {
      const index = this.selectedArchivedIds.indexOf(itemId);
      if (index > -1) {
        this.selectedArchivedIds.splice(index, 1);
      } else {
        this.selectedArchivedIds.push(itemId);
      }
    },
    toggleSelectAll() {
      const currentPageItemIds = this.paginatedArchivedTodos.map(item => item.id);
      if (this.isAllSelected) {
        this.selectedArchivedIds = this.selectedArchivedIds.filter(id => !currentPageItemIds.includes(id));
      } else {
        const newSelectedIds = new Set([...this.selectedArchivedIds, ...currentPageItemIds]);
        this.selectedArchivedIds = Array.from(newSelectedIds);
      }
    },
    async deleteSelectedItems() {
      if (this.selectedCount === 0) return;
      try {
        await this.deleteArchivedTodosBatch(this.selectedArchivedIds);
        this.selectedArchivedIds = [];
        console.log('Selected archived items deleted successfully.');
      } catch (error) {
        console.error('Error deleting selected archived items:', error);
      }
    },
    async loadArchivedData() {
      if (!this.archivedTodosLoadStatus) {
        this.isLoadingArchived = true;
        try {
          console.log('[ArchivedView.vue] 获取归档待办事项...');
          await this.fetchArchivedTodosFromDisk();
          console.log('[ArchivedView.vue] 归档待办事项获取完成, 数量:', this.getArchivedTodos.length);
        } catch (error) {
          console.error('[ArchivedView.vue] 获取归档待办事项时出错:', error);
        } finally {
          this.isLoadingArchived = false;
        }
      } else {
        console.log('[ArchivedView.vue] 归档数据已加载，跳过重新获取');
      }
    },
    goToArchivePage(pageNumber) {
      if (pageNumber >= 1 && pageNumber <= this.totalPagesArchive) {
        this.currentPageArchive = pageNumber;
      }
    },
    prevArchivePage() {
      if (this.currentPageArchive > 1) {
        this.currentPageArchive--;
      }
    },
    nextArchivePage() {
      if (this.currentPageArchive < this.totalPagesArchive) {
        this.currentPageArchive++;
      }
    },
    setFilterPriorityArchive(priority) {
      this.filterPriorityArchive = priority;
    },
    setFilterStatusArchive(status) {
      this.filterStatusArchive = status;
    }
  },
  watch: {
    searchQuery() {
      this.currentPageArchive = 1;
    },
    filterPriorityArchive() {
      this.currentPageArchive = 1;
    },
    filterStatusArchive() {
      this.currentPageArchive = 1;
    },
    totalPagesArchive(newTotal) {
      if (this.currentPageArchive > newTotal && newTotal > 0) {
        this.currentPageArchive = newTotal;
      } else if (newTotal === 0 || newTotal === 1) {
        this.currentPageArchive = 1;
      }
    },
    getArchivedTodos: {
      handler() {
      },
      deep: true
    }
  },
  created() {
    console.log('[ArchivedView.vue] Component created.');
    this.loadArchivedData();
  }
}
</script>

<style scoped>
.archived-view-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: var(--spacing-lg);
  gap: var(--spacing-md);
  background-color: var(--theme-bg-content-area);
  color: var(--theme-text-primary);
}

.archived-list-container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  overflow: hidden;
  background-color: var(--theme-bg-primary);
  border-radius: var(--border-radius-lg);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  padding: var(--spacing-base);
}

/* New styles for the solo search bar container */
.search-bar-archive-solo {
  padding-bottom: var(--spacing-base); /* Add space below search bar */
  /* border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary); /* Optional separator */
}

.search-bar-archive-solo .search-input {
  width: 100%; /* Make search input take full width of this container */
}

.select-all-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: var(--spacing-base);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
  gap: var(--spacing-lg);
}

.select-actions-group {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  flex-shrink: 0;
}

.checkbox-style {
  appearance: none;
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-sm);
  background-color: var(--theme-bg-input);
  cursor: pointer;
  position: relative;
  flex-shrink: 0;
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
}

.checkbox-style:checked {
  background: var(--theme-accent-primary);
  border-color: transparent;
}

.checkbox-style:checked::after {
  content: '';
  position: absolute;
  left: 6px;
  top: 3px;
  width: 5px;
  height: 10px;
  border: solid var(--theme-text-on-accent);
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-style:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.select-all-bar label {
  color: var(--theme-text-secondary);
  cursor: pointer;
  user-select: none;
  font-size: var(--font-size-sm);
}

.select-all-bar label:hover {
  color: var(--theme-text-primary);
}

.delete-selected-button {
  padding: var(--spacing-xs) var(--spacing-sm);
  font-size: var(--font-size-sm);
  color: var(--theme-text-on-accent);
  background-color: var(--theme-button-danger-bg);
  border: var(--border-width) var(--border-style) transparent;
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.delete-selected-button .button-icon {
  font-family: var(--font-family-icons);
  font-size: var(--font-size-base);
}

.delete-selected-button:hover:not(:disabled) {
  background-color: var(--theme-button-danger-bg-hover);
  filter: brightness(1.1);
}

.delete-selected-button:disabled {
  color: var(--theme-text-disabled);
  background-color: color-mix(in srgb, var(--theme-button-danger-bg) 50%, transparent);
  border-color: var(--theme-border-primary);
  cursor: not-allowed;
}

.search-input {
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  min-width: 200px;
}

.search-input::placeholder {
  color: var(--theme-text-muted);
}

.search-input:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.archived-list-section {
  flex-grow: 1;
  overflow-y: auto;
  padding: var(--spacing-xs) 0;
}

.loading-message,
.empty-list-message {
  text-align: center;
  padding: var(--spacing-xl) var(--spacing-base);
  color: var(--theme-text-muted);
  font-style: italic;
  margin-top: var(--spacing-lg);
}

.archived-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.archived-item {
  display: flex;
  align-items: flex-start;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-card);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
  gap: var(--spacing-md);
}

.archived-item:hover {
  border-color: var(--theme-border-secondary);
  background-color: var(--theme-bg-hover);
}

.archived-item.selected {
  background-color: color-mix(in srgb, var(--theme-accent-primary) 20%, var(--theme-bg-card));
  border-color: var(--theme-accent-primary);
}

.item-checkbox {
  margin-top: 3px;
}

.item-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xxs);
  flex-grow: 1;
  min-width: 0;
}

.item-main-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.priority-indicator-archived {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
}

.item-text {
  color: var(--theme-text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-grow: 1;
}

.archived-item.completed .item-text {
  color: var(--theme-text-muted);
  text-decoration: line-through;
  text-decoration-color: var(--theme-text-disabled);
}

.item-meta-line {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-md);
  font-size: var(--font-size-xs);
  color: var(--theme-text-muted);
}

.item-status,
.item-archived-date {
}

.archived-footer {
  padding: var(--spacing-sm) var(--spacing-base);
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  background-color: var(--theme-bg-secondary);
  flex-shrink: 0;
}

.priority-legend-container-archived {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: var(--spacing-md);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
}

.legend-text {
}

/* Styles for Priority Filter Bar */
.filter-priority-bar-archive {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  flex-shrink: 0;
}

.filter-priority-bar-archive .filter-label {
  font-size: var(--font-size-sm);
  color: var(--theme-text-secondary);
  margin-right: var(--spacing-xs);
  font-weight: var(--font-weight-medium);
}

.filter-priority-bar-archive button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.filter-priority-bar-archive button:hover {
  border-color: var(--theme-accent-primary);
  color: var(--theme-accent-primary);
}

.filter-priority-bar-archive button.active {
  background: var(--theme-accent-gradient);
  color: var(--theme-text-on-accent);
  border-color: transparent;
  font-weight: var(--font-weight-medium);
}

.filter-priority-bar-archive button .priority-dot-filter {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
}

.filter-priority-bar-archive button.active .priority-dot-filter {
   border: 1px solid rgba(0,0,0,0.1); /* Ensure visibility on active button */
}

/* Styles for Pagination Controls */
.pagination-controls-archive {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: var(--spacing-base) 0;
  gap: var(--spacing-md);
  flex-shrink: 0;
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary); 
  /* Match styling from other views */
}

.pagination-controls-archive .pagination-button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
}

.pagination-controls-archive .pagination-button:hover:not(:disabled) {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-primary);
}

.pagination-controls-archive .pagination-button:disabled {
  color: var(--theme-text-disabled);
  background-color: color-mix(in srgb, var(--theme-bg-button-secondary) 50%, transparent);
  border-color: var(--theme-border-primary);
  cursor: not-allowed;
}

.pagination-controls-archive .pagination-info {
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}

/* New styles for the right-side container of ONLY filters */
.filters-archive-right-group {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg); /* Gap between status and priority filter groups */
}

/* Styles for Status Filter Bar */
.filter-status-bar-archive {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  flex-shrink: 0; /* Consistent with priority filter bar */
}

.filter-status-bar-archive .filter-label {
  font-size: var(--font-size-sm);
  color: var(--theme-text-secondary);
  margin-right: var(--spacing-xs);
  font-weight: var(--font-weight-medium);
}

.filter-status-bar-archive button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
  font-size: var(--font-size-sm);
  /* display: flex; align-items: center; gap: var(--spacing-xs); Already good if no icons */
}

.filter-status-bar-archive button:hover {
  border-color: var(--theme-accent-primary);
  color: var(--theme-accent-primary);
}

.filter-status-bar-archive button.active {
  background: var(--theme-accent-gradient);
  color: var(--theme-text-on-accent);
  border-color: transparent;
  font-weight: var(--font-weight-medium);
}
</style>